//
//  ZZCPropertyController.m
//  ZZC-Finance
//
//  Created by mac on 2017/5/22.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "ZZCPropertyController.h"
#import "ZZCNameController.h"
#import "ZZCChangePhoneOneController.h"
#import "ZZCAddressController.h"
#import "ZZCBankCardController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "ZZCPerfectController.h"
#import "ZZCCompanyInfoController.h"
#import "ZZCCompanyInfoStatusController.h"
#import "ZZCMeInfo.h"
@interface ZZCPropertyController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (copy, nonatomic) NSString *stateType;
@end

@implementation ZZCPropertyController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"个人信息";
    [self attributeValue];
    
}
//属性赋值
- (void)attributeValue {
    //头像
    NSURL *url = [NSURL URLWithString:self.imgUrl];
    [self.iconView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"1.jpeg"]];
    self.iconView.clipsToBounds = YES;
    //等级
    self.rankLabel.text = self.meInfoModel.grade;
    //余额
    self.balanceLabel.text = [NSString stringWithFormat:@"%@U币",self.meInfoModel.money];
    //可用额度
    self.quotaLabel.text = self.meInfoModel.money_ed;
    //手机号
    self.phoneLabel.text = self.meInfoModel.phone;
    //昵称
    self.nameLabel.text = self.meInfoModel.nickname;
//    NSLog(@"^^^^^^^^^^^^^^^%@",self.meInfoModel.nickname);
    
    
    //给view添加手势
    self.imgView.userInteractionEnabled = YES;
    UITapGestureRecognizer *imgTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imgClick)];
    [self.imgView addGestureRecognizer:imgTap];
    
    self.nameView.userInteractionEnabled = YES;
    UITapGestureRecognizer *nameTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(nameClick)];
    [self.nameView addGestureRecognizer:nameTap];
    
    self.phoneView.userInteractionEnabled = YES;
    UITapGestureRecognizer *phoneTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(phoneClick)];
    [self.phoneView addGestureRecognizer:phoneTap];
    
    self.bankView.userInteractionEnabled = YES;
    UITapGestureRecognizer *bankTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bankClick)];
    [self.bankView addGestureRecognizer:bankTap];
    
    self.addressView.userInteractionEnabled = YES;
    UITapGestureRecognizer *addressTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addressClick)];
    [self.addressView addGestureRecognizer:addressTap];
    
    self.perfectView.userInteractionEnabled = YES;
    UITapGestureRecognizer *perfectTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(perfectClick)];
    [self.perfectView addGestureRecognizer:perfectTap];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadSucceedData) name:@"changeNameSucceed" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadSucceedData) name:@"changePhoneSucceed" object:nil];

}

- (void)reloadSucceedData {
    self.nameLabel.text =   ZZCNSUserDefaults(@"NICK_NAME");
    self.phoneLabel.text = ZZCNSUserDefaults(@"userphone");
    NSLog(@"88888888888888888888");
}
#pragma mark -view的点击事件

//头像
- (void)imgClick {
    ZZCLog(@"你点击了头像");
    [self userEvent];

}

//名字
- (void)nameClick {
    ZZCLog(@"你点击了名字");
    ZZCNameController *name = [ZZCNameController new];
    name.nameStr = self.nameLabel.text;
    [self.navigationController pushViewController:name animated:YES];
}
//手机号
- (void)phoneClick {
    ZZCLog(@"你点击了手机号");
    ZZCChangePhoneOneController *phone = [ZZCChangePhoneOneController new];
    [self.navigationController pushViewController:phone animated:YES];
}
//银行卡
- (void)bankClick {
    ZZCLog(@"你点击了银行卡");
    ZZCBankCardController *bank = [ZZCBankCardController new];
    [self.navigationController pushViewController:bank animated:YES];
}
//地址
- (void)addressClick {
    ZZCLog(@"你点击了地址");
    ZZCAddressController *address = [ZZCAddressController new];
    [self.navigationController pushViewController:address animated:YES];
}
//完善信息
- (void)perfectClick {
    ZZCLog(@"你点击了完善信息");
    BOOL is_company = [[NSUserDefaults standardUserDefaults] integerForKey:@"IS_COMPANY"];
    if (!is_company) {
        NSLog(@"为个人用户");
        ZZCPerfectController *property = [ZZCPerfectController new];
        [self.navigationController pushViewController:property animated:YES];
    } else {
        //判断状态
        [self checkState];
    }
}
- (void)checkState {
    ZZCLog(@"判断状态");
    NSDictionary *token = ZZCNSUserDefaults(@"token");
    
    NSDate *currentDate = [NSDate date];
    NSString *timeStr = [NSString stringWithFormat:@"%ld",(long)[currentDate timeIntervalSince1970]];
    NSDictionary *dict = @{
                           @"token":token,
                           };
    
    NSString *sign = [ZZCRequest getSignWithDict:dict];
    sign = [NSString md5:[sign lowercaseString]];
    NSDictionary *param = @{
                            @"timestamp":timeStr,
                            @"sign":sign,
                            @"token":token,
                            };
    NSLog(@"%@",param);
    [[ZZCRequest sharedNetworkTools] POST:ZZCURL_API_AGENTMESS parameters:param finished:^(id  _Nullable responseObject, NSError * _Nullable error) {
        [SVProgressHUD showInfoWithStatus:responseObject[@"info"]];
        NSLog(@"%@",responseObject);
        if ([responseObject[@"code"] isEqual:@(200)]) {
            ZZCCompanyInfoStatusController *infoStatusVC = [ZZCCompanyInfoStatusController new];
            [self.navigationController pushViewController:infoStatusVC animated:YES];
        } else {
            ZZCCompanyInfoController *infoVC = [ZZCCompanyInfoController new];
            [self.navigationController pushViewController:infoVC animated:YES];
        }
    }];
    
}

//调用相机
- (void)userEvent {
    [self cameraBtnDidClick];
}

-(void)cameraBtnDidClick{
    
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    alertController.view.tintColor = [UIColor colorWithHex:0xEB6927];
    UIAlertAction * photo = [UIAlertAction actionWithTitle:@"拍照" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self openPhotoWithType:1];
    }];
    
    UIAlertAction * choice = [UIAlertAction actionWithTitle:@"相册选择" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self openPhotoWithType:0];
    }];
    
    UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style: UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        
    }];
    
    [alertController addAction:photo];
    [alertController addAction:choice];
    [alertController addAction:cancel];
    [self showDetailViewController:alertController sender:nil];
    
}

#pragma mark - 相册 相机
- (void)openPhotoWithType:(int)type
{
    if ([self getMediaTypeVideo]) {  //获取相机权限
        UIImagePickerControllerSourceType sourceType = type;
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];//初始化
        picker.delegate = self;
        picker.allowsEditing = YES;//设置可编辑
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:nil];//进入照相界面
    }else{
        [[[UIAlertView alloc] initWithTitle:nil
                                    message:@"请设置使用照片。\n请启用照片-设置/隐私/照片"
                                   delegate:nil
                          cancelButtonTitle:@"OK"
                          otherButtonTitles:nil, nil] show];
        
        NSLog(@"相机受限");
    }
}

#pragma mark 判断摄像头权限
-(bool)getMediaTypeVideo
{
    ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
    
    if(author == ALAuthorizationStatusRestricted){// 受限制 家长权限之类的
        
        return NO;
        
    } else if(author == ALAuthorizationStatusDenied){// 已经拒绝的
        
        [[[UIAlertView alloc] initWithTitle:nil
                                    message:@"请设置使用照片。\n请启用照片-设置/隐私/照片"
                                   delegate:nil
                          cancelButtonTitle:@"OK"
                          otherButtonTitles:nil, nil] show];
        return NO;
    } else if(author == ALAuthorizationStatusAuthorized){// 已允许的
        
        return YES;
        
    } else if(author == ALAuthorizationStatusNotDetermined){// 还没决定的
        
        return YES;
    } else {
        
        return NO;
    }
}
#pragma mark - imagePicker delegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    UIImage *img = [self scaleToSize:[info objectForKey:@"UIImagePickerControllerEditedImage"] size:CGSizeMake(300, 300)];
    ZZCLog(@"%@",img);
    [self uploadImage:img];
    
}
- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size
{
    UIGraphicsBeginImageContext(size);
    [img drawInRect:CGRectMake(0,0, size.width, size.height)];
    UIImage* scaledImage =UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

#pragma mark - 上传图片
- (void)uploadImage:(UIImage *)img {
    NSString *token = ZZCNSUserDefaults(@"token");
    NSDictionary *param = @{@"token":token,@"type":@(1)};
    [[ZZCRequest sharedNetworkTools] uploadWithURL:ZZCURL_API_UPLOAD params:param formBoundary:img success:^(NSDictionary * _Nonnull data) {
        ZZCLog(@"%@",data);
        self.imgUrl = data[@"data"][@"url"];
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",ZZCURL_API,self.imgUrl]];
        [self.iconView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"未登录头像"]];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updetaMeInfo" object:self];
        [SVProgressHUD showInfoWithStatus:data[@"msg"]];
        NSLog(@"头像网址%@",url);
    } fail:^(NSError * _Nonnull error, NSString * _Nonnull msg, NSDictionary * _Nonnull data) {
        ZZCLog(@"%@",error);
    }];
     
}
@end
